package com.uy.cuantoconocesdeuruguay;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.uy.cuantoconocesdeuruguay.adapters.FriendsViewAdapter;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.datatypes.FacebookDeviceUser;
import com.uy.cuantoconocesdeuruguay.datatypes.FacebookUser;
import com.uy.cuantoconocesdeuruguay.dialogs.ErrorOccurredDialogUtils;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.listeners.ShakeListener;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;
import com.uy.cuantoconocesdeuruguay.utiles.ApplicationUtils;
import com.uy.cuantoconocesdeuruguay.utiles.FacebookHelper;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;

@SuppressLint("NewApi") 
public class FriendsRanking extends BaseActivity {
    private static HashMap<String,FacebookUser> friendsList;

	private SensorManager mSensorManager;
	private ShakeListener mSensorListener;
	private LinearLayout loaderLayoutLayout;
	private ListView listview;
	private boolean visible;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friends_ranking);
		if (savedInstanceState != null) {
			return;
		}
		
		View friendsRankingLayout = findViewById(R.id.friendsRankingLayout);
		boolean isTablet = getResources().getBoolean(R.bool.isTablet);
		if (isTablet){
			friendsRankingLayout.setBackgroundResource(R.drawable.friends_bg_tablets);
		}
		Drawable background = friendsRankingLayout.getBackground();
		background.setAlpha(221);
		
		loaderLayoutLayout = (LinearLayout)findViewById(R.id.loaderLayout);
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorListener = new ShakeListener();		
		getSystemService(Context.VIBRATOR_SERVICE);
		fetchFriends();		
	}
	private void fetchFriends(){
		initRefreshLoader(true);
		AsyncTask<Void, Void, Boolean> friendsLoader = new AsyncTask<Void, Void, Boolean>(){
			private ArrayAdapter<String> adapter;
			@Override
			protected Boolean doInBackground(Void... params) {
				try{
					int count = 0;
					while (!MainActivity.userData.isFacebookLoaded() && count < 400){//WAIT 10 seconds
						try {
							Thread.sleep(50);
							++count;
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					if (count >= 400){
						ApplicationUtils.restartApplication(FriendsRanking.this);
					}
					if (MainActivity.userData.getFacebookid() == null){
						return false;
					}
					adapter = loadDataOnList();
					return adapter != null;
				}catch (Exception e){
					GoogleAnalyticsTracker.trackException(FriendsRanking.this, e);
					e.printStackTrace();
				}
				return false;
			}
			@Override
			protected void onPostExecute(Boolean success) {
				if (isFinishing() || !visible){
					finish();
					return;
				}
				try{
					if (success){
						if (adapter == null){
							Toast.makeText(FriendsRanking.this, getString(R.string.friend_ranking_no_friends_playing), Toast.LENGTH_SHORT).show();
						}else{
							listview.setAdapter(adapter);
						}
						Toast.makeText(FriendsRanking.this, getString(R.string.shake_to_refresh), Toast.LENGTH_SHORT).show();
						initRefreshLoader(false);
	
						mSensorListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
							public void onShake() {
								fetchFriends();
							}
						});
					}else{
						ApplicationUtils.restartApplication(FriendsRanking.this);
					}
				}catch (Exception e){
					e.printStackTrace();
					GoogleAnalyticsTracker.trackException(FriendsRanking.this, e);
					ApplicationUtils.restartApplication(FriendsRanking.this);
				}
			}
		};
		if (android.os.Build.VERSION.SDK_INT > 10) { 
			friendsLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			friendsLoader.execute();
		}
	}
	private void initRefreshLoader(boolean start) {	
		if (start){
			loaderLayoutLayout.setVisibility(View.VISIBLE);
		}else{
			loaderLayoutLayout.setVisibility(View.GONE);
		}
	}
	
	public ArrayAdapter<String> loadDataOnList(){
		getUserFriends(FriendsRanking.this); 
		String onlyMeList = StringPool.APOSTROFE+MainActivity.userData.getFacebookid()+StringPool.APOSTROFE_COMMA;//ADD 'ME' TO THE LIST
		String listOfFriendsIds = onlyMeList;
		for (String id : friendsList.keySet()){
			listOfFriendsIds += StringPool.APOSTROFE+id+StringPool.APOSTROFE_COMMA;
		}
		
		if (listOfFriendsIds.equals(onlyMeList)){
			return null;
		}else{
			listOfFriendsIds = listOfFriendsIds.substring(0, listOfFriendsIds.length()-1);
			List<FacebookDeviceUser> listOfScores = null;
			try{
				listOfScores = ServerConnector.getFriendsScores(listOfFriendsIds);
			}catch (ConnectivityException e){
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(FriendsRanking.this, e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
				return null;
			}
			LinkedList<FacebookUser> friendsPlaying = new LinkedList<FacebookUser>();
			for (FacebookDeviceUser user : listOfScores){
				FacebookUser facebookUser = friendsList.get(user.getFacebookid());
				facebookUser.setScore(user.getScore());
				facebookUser.setCorrectImages(user.getCorrectImages());
				facebookUser.setTotalImages(user.getTotalImages());
				facebookUser.setCorrectQuestions(user.getCorrectQuestions());
				facebookUser.setTotalQuestions(user.getTotalQuestions());
				facebookUser.setPercentageCompleted(user.getPercentageCompleted());
				friendsPlaying.add(facebookUser);
			}
			String[] entries = new String[friendsPlaying.size()];
			for (int i=0 ; i< friendsPlaying.size() ; ++i) {
				FacebookUser user = friendsPlaying.get(i);
				entries[i] = user.getId();
				++i;
			}
			final FriendsViewAdapter adapter = new FriendsViewAdapter(FriendsRanking.this, entries, friendsPlaying);
			listview = (ListView) findViewById(R.id.friendsList);
			return adapter;		
		}
	}

	@Override
	public void onBackPressed() {
		Intent i = new Intent(getApplicationContext(), MainActivity.class);
		startActivity(i);
		finish();
	}
	
	private static void getUserFriends(Activity activity){
		boolean done = false;
		while (!done){
			try{
				friendsList = FacebookHelper.getAllFriends(activity);				
				FacebookUser me = new FacebookUser();
				String[] nameTokens = MainActivity.userData.getFacebookName().split(StringPool.SPACE);
				me.setFirst_name(nameTokens[0]);
				me.setLast_name(nameTokens[1]);
				me.setId(MainActivity.userData.getFacebookid());
				me.setPicture(MainActivity.userData.getFacebookImage());
				friendsList.put(me.getId(),me);
				done = true;
			}catch (Exception e){
				GoogleAnalyticsTracker.trackException(activity, e);
				e.printStackTrace();
			}
		}
	}
	public static FacebookUser getFriend(Activity activity, String facebookId){
		if (friendsList == null){
			getUserFriends(activity); 
		}
		return friendsList.get(facebookId);
	}
	@Override
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_UI);
		visible = true;
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		visible = false;
		super.onPause();
	}
	@Override
	public void trackScreen() {
		GoogleAnalyticsTracker.trackScreen(this, "Listado ranking de amigos");
	}
}
